from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from rest_framework.response import Response
from rest_framework.views import APIView


from apps.active.models import Gathering
from utils.token_jwt import check_token


# Create your views here.

# 活动列表
class ActiveView(APIView):
    def get(self,request):
        data = Gathering.objects.all()
        list1 = []
        for i in data:
            # user = [i.id for i in i.users.all().values_list('id')]
            list1.append({
                'id':i.id,
                'name':i.name,
                'city':i.city,
                'image':'http://s7g9jujrf.hn-bkt.clouddn.com/' +str(i.image),
                'starttime':i.starttime,
                'endrolltime':i.endrolltime,
                # 'user':user
            })
        return JsonResponse({'results':list1})

# 活动详情
class ActiveDetailView(APIView):
    def get(self,request,id):
            i = Gathering.objects.filter(id=id).first()
            list1 = []
            list1.append({
                'id':i.id,
                'name':i.name,
                'summary':i.summary,
                'address':i.address,
                'sponsor':i.sponsor,
                'image': 'http://s7g9jujrf.hn-bkt.clouddn.com/' +str(i.image)  ,
                'city':i.city,
                'state':1,
                'starttime':i.starttime,
                'endtime':i.endtime,
                'endrolltime':i.endrolltime,
                # 'user':
            })
            return JsonResponse({'data':list1})






class JoinGatheringView(APIView):
    def post(self, request, id):
        token = request.META.get('HTTP_AUTHORIZATION')
        if not token:
            return Response({'message': '用户未登录', 'success': False})
        user_data = check_token(token.split(' ')[1])
        if not user_data:
            return Response({'message': '用户身份验证失败', 'success': False})
        user_id = user_data.get('user_id')  # 从字典中获取用户ID
        try:
            gathering = Gathering.objects.get(id=id)
        except Gathering.DoesNotExist:
            return Response({'message': '活动不存在', 'success': False})

        if gathering.users.filter(id=user_id).exists():  # 使用用户ID进行过滤
            gathering.users.remove(user_id)
            gathering.save()
            request.session['state'] = 0  # 设置会话变量为False
            return Response({'message': '取消报名成功', 'success': True})
        else:
            gathering.users.add(user_id)
            gathering.save()
            request.session['state'] = 1  # 设置会话变量为True
            return Response({'message': '报名成功', 'success': True})

